package xin.config.db;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;

/**
 * <pre>
 * 德鲁伊数据源配置
 * </pre>
 *
 * @author lixin_ma@outlook.com
 * @version 1.0
 * @since 2018/7/28 14:35
 */
@Configuration
@Slf4j
public class DbConfiguration implements EnvironmentAware {
    private Environment environment;

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @Value("${spring.datasource.url}")
    private String dbUrl;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;

    /**
     * 初始化大小，最大
     */
    @Value("${spring.datasource.druid.initialSize}")
    private int initialSize;

    @Value("${spring.datasource.druid.minIdle}")
    private int minIdle;

    @Value("${spring.datasource.druid.maxActive}")
    private int maxActive;

    /**
     * 配置获取连接等待超时的时间
     */
    @Value("${spring.datasource.druid.maxWait}")
    private int maxWait;

    /**
     * 配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
     */
    @Value("${spring.datasource.druid.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;

    /**
     * 配置一个连接在池中最小生存的时间，单位是毫秒
     */
    @Value("${spring.datasource.druid.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;

    @Value("${spring.datasource.druid.validationQuery}")
    private String validationQuery;

    @Value("${spring.datasource.druid.testWhileIdle}")
    private boolean testWhileIdle;

    @Value("${spring.datasource.druid.testOnBorrow}")
    private boolean testOnBorrow;

    @Value("${spring.datasource.druid.testOnReturn}")
    private boolean testOnReturn;

    /**
     * 打开PSCache，并且指定每个连接上PSCache的大小
     */
    @Value("${spring.datasource.druid.poolPreparedStatements}")
    private boolean poolPreparedStatements;

    @Value("${spring.datasource.druid.maxPoolPreparedStatementPerConnectionSize}")
    private int maxPoolPreparedStatementPerConnectionSize;

    /**
     * 配置监控统计拦截的filters，去掉后监控界面sql无法统计，'wall'用于防火墙
     */
    @Value("${spring.datasource.druid.filters}")
    private String filters;

    /**
     * 通过connectProperties属性来打开mergeSql功能；
     * 慢SQL记录 connectionProperties:
     * druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
     */
    @Value("${spring.datasource.druid.connectionProperties}")
    private String connectionProperties;

    /**
     * 物理连接初始化的时候执行的sql
     */
    @Value("${spring.datasource.druid.connectionInitSqls}")
    private String connectionInitSqls;

    @Bean
    @Primary
    public DataSource dataSource() throws SQLException {
        log.info(">>>>>>>Druid Config>>>>>>>>>>>>>>>>>>>");
        log.info(">>url:{}",dbUrl);
        log.info(">>user:{}",username);
        log.info(">>driver:{}",driverClassName);
        log.info(">>maxWait:{}",maxWait);
        log.info(">>maxActive:{}",maxActive);
        log.info(">>minIdle:{}",minIdle);
        log.info(">>>>>>>Druid Config>>>>>>>>>>>>>>>>>>>");
        if (StringUtils.isEmpty(dbUrl)) {
            log.error("Your database connection pool configuration is incorrect! Please check your Spring profile, current profiles are:{}"
                    , Arrays.toString(environment.getActiveProfiles()));
            throw new ApplicationContextException("Database connection pool is not configured correctly");
        }

        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(dbUrl);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setDriverClassName(driverClassName);

        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        datasource.setFilters(filters);
        datasource.setConnectionProperties(connectionProperties);
        datasource.setConnectionProperties(connectionInitSqls);
        return datasource;
    }

    @Bean
    public DataSourceTransactionManager transactionManager(DataSource dataSource){
        log.info("Spring Jdbc TransactionManager Init");
        DataSourceTransactionManager txnm = new DataSourceTransactionManager();
        txnm.setDataSource(dataSource);
        return txnm;
    }
}
